<template>
  <!-- 大客户线索管理->经销商大客户区域经理维护 -->
  <div>
    <!-- 搜索 -->
    <FormPanel
      ref="formPanel"
      :list="initForm"
      :cols="3"
      :labelWidth="120"
      :isSubmitBtn="false"
      :formType="dataFromType"
      @formChange="formChangeHandle"
    />
    <!-- table -->
    <FilterTable
      ref="table"
      :visible.sync="visibleDealer"
      :columns="columns"
      :isSelectColumn="isSelectColumn"
      :dataSource="dataSource"
      columnsRef='customerManage_clue_areaBossOperation_info_01'
      :onColumnsChange="columns => this.columns = columns"
    >
      <template slot="controls">
        <el-button size="small" type="primary" @click="dealerHandle">选择经销商</el-button>
      </template>
    </FilterTable>
    <!-- 区域经理弹窗 -->
    <BaseDialog
      title="区域经理选择"
      width="900px"
      destroyOnClose
      :visible.sync="visiblePersonnel"
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <personnel-madal ref="personnelDialog" @close="closePersonnel" />
    </BaseDialog>

    <Drawer
      :visible.sync="visibleDealer"
      title="经销商选择"
      :width="920"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <dealer-madal selectType="multiple" v-model="initDealerData" @close="closeDealer" />
    </Drawer>
    <div class="dialogBottmView">
      <el-button @click="closeDialog">取 消</el-button>
      <MultiuseButton :click="saveDialog" type="primary">保 存</MultiuseButton>
    </div>
  </div>
</template>
<script>
import personnelMadal from '@/pages/cms-common/user/index';
import dealerMadal from '@/pages/cms-common/dealerdata';
import infoModal from '../createClue/info';
import { dictionary } from '@/utils/dictMixin';
import { region } from '@/api/cms-common/region'; //行政区域
import { PHONE_PATTERN } from '@/utils/validate'; // 验证
import { getManageDealerList, insertManager, updateManager, getManagerById } from '@/api/cms-api/customerManage/clue/areaBossOperation'; //大客户区域经理维护
import { type } from 'os';
import { Notification } from 'element-ui';
export default {
  name: 'customerAdd',
  mixins: [dictionary, region],
  components: {
    infoModal,
    dealerMadal,
    personnelMadal
  },
  props: {
    formType: {
      type: String,
      default: 'add'
    },
    managerId: {
      type: Number,
      default: -1
    }
  },
  data() {
    return {
      dataFromType: this.formType,
      visibleDealer: false, //添加经销商
      initDealerData: {}, //经销商弹窗参数
      visiblePersonnel: false, //选择区域经理
      isSelectColumn: false,
      dataSource: [], //经销商查询数据
      userId: '', //大客户经理对应区域ID
      initForm: this.initFormFun(),
      columns: this.creatHeader(),
      formData: {}, //保存大客户经理数据
      dealerQueryParams: { pageNum: 1, currentPage: 1, pageSize: 9999, limit: 9999, managerId: this.managerId } //ipa 接口
    };
  },
  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
  },
  methods: {
    //搜索数据
    initFormFun() {
      return [
        {
          type: 'SELECT', //1
          label: '大客户事业部',
          fieldName: 'majorManagerId',
          placeholder: '请输入',
          initialValue: '',
          rules: [{ required: true, message: '必填', trigger: 'blur' }], //验证
          itemList: this.createDictList('2566')
        },
        {
          type: 'INPUT', //2
          label: '区域经理代码',
          fieldName: 'employeeNo',
          placeholder: '请选择',
          initialValue: '',
          unitRender: () => {
            return <el-button slot="append" icon="el-icon-search" onClick={() => this.personnelHandle()}></el-button>;
          },
          rules: [{ required: true, message: '必填', trigger: 'blur' }] //验证
        },
        {
          type: 'INPUT', //3
          label: '区域经理姓名',
          fieldName: 'majorSbuManagerName',
          placeholder: '',
          disabled: true,
          initialValue: ''
        },
        {
          type: 'INPUT', //4
          label: '性别',
          fieldName: 'gender',
          placeholder: '',
          disabled: true,
          initialValue: ''
        },
        {
          type: 'INPUT', //5
          label: '手机',
          fieldName: 'phone',
          placeholder: '',
          disabled: true,
          initialValue: ''
        },
        {
          type: 'INPUT', //6
          label: '身份证号',
          fieldName: 'idCardNum',
          placeholder: '',
          disabled: true,
          initialValue: ''
        },
        {
          type: 'SELECT', //7
          label: '状态',
          fieldName: 'status',
          placeholder: '请选择',
          initialValue: 10011001,
          itemList: this.createDictList('1001'),
          rules: [{ required: true, message: '必填', trigger: 'blur' }] //验证
        }
      ];
    },
    //搜索获取数据
    async formChangeHandle(val) {
      this.formData = val;
    },
    //保存大客户区域经理信息
    async saveAreaManager(managerData) {
      if (this.formType == 'add') {
        //新增
        let res = await insertManager(managerData);
        this.ajaxBackDeal(res);
      } else {
        //修改
        let res = await updateManager(this.managerId, managerData);
        this.ajaxBackDeal(res);
      }
    },
    //table表头和数据源
    creatHeader() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.$index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 50,
          fixed: 'left',
          render: (props, h) => {
            return (
              <div>
                <el-button size="mini" type="text" onClick={() => this.deleteHandle(props.row)}>
                  删除
                </el-button>
              </div>
            );
          }
        },
        // { title: '公司全称', dataIndex: 'companyName', sorter: true },
        { title: '公司全称', dataIndex: 'dealerName', sorter: true },
        { title: '经销商代码', dataIndex: 'ownerCode', sorter: true },
        // { title: '经销商简称', dataIndex: 'dealerName', sorter: true },
        { title: '经销商简称', dataIndex: 'dealerShortname', sorter: true },
        {
          title: '经销商类型',
          dataIndex: 'dealerType',
          sorter: true,
          render: props => {
            return <span>{this.createDictText(props.row.dealerType, '2538')}</span>;
          }
        },
        {
          title: '经销商级别',
          dataIndex: 'shopLevel',
          sorter: true,
          render: props => {
            return <span>{this.createDictText(props.row.shopLevel, '2540')}</span>;
          }
        },
        { title: '事业部', dataIndex: 'deptName', sorter: true },
        { title: '办事处', dataIndex: 'officeName', sorter: true },
        {
          title: '省',
          dataIndex: 'provinceId',
          sorter: true,
          render: props => {
            //编码转汉字
            return <span>{this.createRegionText(props.row.provinceId)}</span>;
          }
        },
        {
          title: '市',
          dataIndex: 'cityId',
          sorter: true,
          render: props => {
            //编码转汉字
            return <span>{this.createRegionText(props.row.cityId)}</span>;
          }
        },
        {
          title: '县/区',
          dataIndex: 'districtId',
          sorter: true,
          render: props => {
            //编码转汉字
            return <span>{this.createRegionText(props.row.districtId)}</span>;
          }
        }
      ];
    },
    // 选择人员
    personnelHandle() {
      this.visiblePersonnel = true;
    },
    // 选择人员-关闭
    closePersonnel(data) {
      if (data.type == 'close') {
        this.visiblePersonnel = data.visible;
        return;
      }
      //返回数据逻辑自己写
      if (data && data.data && typeof data.data != 'undefined') {
        this.initForm[1].initialValue = data.data[0].employeeNo; //代码
        this.initForm[2].initialValue = data.data[0].employeeName; //姓名
        this.initForm[3].initialValue = this.createDictText(data.data[0].gender,'1002'); //性别
        this.initForm[4].initialValue = data.data[0].mobilePhone; //手机
        this.initForm[5].initialValue = data.data[0].certificateId; //身份证号
        this.userId = data.data[0].userId; //userId
      }
      this.visiblePersonnel = data.visible; //关闭弹窗
    },
    // 经销商打开窗口 -传数据
    dealerHandle() {
      this.initDealerData = {
        excludeBigCustomer: false, //是否查询大客户经销商，如果查询 true，不查询 false
        id: 10011020
      };
      this.visibleDealer = true;
    },
    productHandle() {
      this.visibleProduct = true;
    },
    //删除列表中经销商
    deleteHandle(row) {
      this.$confirm('确认删除', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.dataSource.splice(row.index, 1);
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
    },
    //判断经销商是否已经在列表中选择
    isExistInDatasouce(dealerCode) {
      let r = false;
      if (this.dataSource && this.dataSource.length > 0) {
        for (let dIdx = 0; dIdx < this.dataSource.length; dIdx++) {
          let tcode = this.dataSource[dIdx].ownerCode;
          if (tcode == dealerCode) {
            r = true;
            break;
          }
        }
      }
      return r;
    },
    //添加选择经销商到列表中
    addSelectDealer(dealers) {
      if (dealers != null && typeof dealers != 'undefined' && dealers.length > 0)
        dealers.forEach(dealer => {
          let dealerCode = dealer.dealerCode;
          if (!this.isExistInDatasouce(dealerCode)) {
            let dealerNode = {
              deptName: dealer.deptName,
              dealerName: dealer.dealerName,
              dealerShortname: dealer.dealerShortname,
              ownerCode: dealer.dealerCode,
              dealerId: null,
              // companyName: dealer.companyName,
              shopLevel: dealer.shopLevel,
              relationId: -1,
              managerId: 1,
              cityId: dealer.cityId,
              provinceId: dealer.provinceId,
              districtId: dealer.districtId,
              isDeleted: '0',
              majorManagerId: null,
              dealerType: dealer.dealerType
            };
            this.dataSource.push(dealerNode);
          }
        });
    },
    // 经销商关闭窗口 -返回数据
    closeDealer(data) {
      this.addSelectDealer(data.data);
      //返回数据逻辑自己写
      this.visibleDealer = data.visible; //关闭弹窗
    },
    //保存
    async saveDialog() {
      let r = await this.$refs.formPanel.GET_FORM_DATA();
      let p = null;
      if (r != null && r.length > 1) {
        p = r[1];
        let isPassValid = r[0]; //是出现异常
        if (!isPassValid) {
          p.userId = this.userId;
          let dealerList = [];
          this.dataSource.forEach(x => {
            let dealer = {};
            dealer.dealerId = x.dealerId;
            dealer.dealerName = x.dealerName;
            dealer.ownerCode = x.ownerCode;
            dealerList.push(dealer);
          });
          p.dealerList = dealerList;
          await this.saveAreaManager(Object.assign({}, p));
        }
      }
    },
    //关闭窗口并传参
    ajaxBackDeal(res) {
      if (res.resultCode == '200') {
        Notification.success({
          title: `提示信息`,
          message: `保存成功！`
        });
        this.$emit('close', { visible: false, type: 'refresh' });
      }else{
        // Notification.error({
        //   title: `提示信息`,
        //   dangerouslyUseHTMLString:true,
        //   duration: 0,
        //   message: `<div style="width: 250px;text-align: left;word-wrap: break-word;">${res.errMsg}</div>`
        // });
      }
    },
    //取消操作
    closeDialog() {
      this.$emit('close', { visible: false, closeType: 'close' });
    },
    closeProduct(data) {
      this.visibleProduct = false;
    },
    //加载区域经销商信息
    loadManageDealerList() {
      getManageDealerList(this.dealerQueryParams).then(res => {
        if (res.resultCode == '200') {
          this.dataSource = res.data.records;
        }
      });
    },
    //加载区域经理信息
    loadManager() {
      getManagerById(this.managerId).then(res => {
        if (res.resultCode == '200') {
          let showData = res.data;
          this.userId = showData.userId;
          this.initForm.forEach(x => {
            if(x.fieldName==='gender'){
              x.initialValue = this.createDictText(showData[x.fieldName],'1002'); //性别
            }else{
              x.initialValue = showData[x.fieldName];
            }
            
          });
        }
      });
    }
  },
  mounted() {
    this.loadManager();
    this.loadManageDealerList();
  }
};
</script>

<style lang="less" scoped>
</style>
